package spring.cloud.tasks.client.item_task_processor;

import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.client.util.CronExpression;

import java.util.Date;
import java.util.Timer;

@Slf4j
public class TaskProcessorScheduleTimerTask extends java.util.TimerTask {
    TaskProcessor taskProcessor;
    Timer itemTaskScheduleTimer;

    String cronExpressionString;

    public TaskProcessorScheduleTimerTask(TaskProcessor taskProcessor, Timer itemTaskScheduleTimer, String cronExpressionString) {
        this.taskProcessor = taskProcessor;
        this.itemTaskScheduleTimer = itemTaskScheduleTimer;
        this.cronExpressionString = cronExpressionString;
    }

    public void run() {
        try {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            this.cancel();
            Date nowDate = new Date(System.currentTimeMillis());
            CronExpression cronExpression = new CronExpression(this.cronExpressionString);
            Date nextRunTime = cronExpression.getNextTimeAfter(nowDate);
            if (taskProcessor.needReInitProcessor) {
                taskProcessor.run("run");
            }
            this.taskProcessor.getTaskProcessorInfo().setNextRunTime(nextRunTime);
            this.taskProcessor.setNextRunTime(nextRunTime);
            this.itemTaskScheduleTimer.schedule(new TaskProcessorScheduleTimerTask(this.taskProcessor, this.itemTaskScheduleTimer, this.cronExpressionString), nextRunTime);
        } catch (Throwable ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}
